<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告 -->
      <el-row class="alert">
        <el-alert
          title="注意:只允许为第三级分类设置相关参数！"
          type="warning"
          show-icon
        >
        </el-alert>
      </el-row>
      <!-- 级联选择器 -->
      <el-row>
        选择商品分类:
        <el-cascader
          expand-trigger="hover"
          v-model="selectedKeys"
          :options="menuInfo"
          :props="paramsProps"
          @change="cateHandleChange"
          clearable
        ></el-cascader>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtn"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyData" border stripe>
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>

            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParams(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtn"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyData" border stripe>
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParams(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
      :title="'添加' + isOk"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeDialog"
    >
      <el-form
        :model="addFormData"
        :rules="addRules"
        ref="addRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="isOk" prop="name">
          <el-input v-model="addFormData.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false" size="mini"
          >取 消</el-button
        >
        <el-button type="primary" @click="addFormReq" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改动态参数/静态属性对话框 -->
    <el-dialog
      :title="'修改' + isOk"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editClose"
    >
      <el-form
        :model="editForm"
        :rules="addRules"
        ref="editRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormReq">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择器选定的值
      selectedKeys: [],
      // 级联选择器数据源
      menuInfo: [],
      // 级联选择器配置对象
      paramsProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 动态/静态
      activeName: "many",
      // 静态数据
      onlyData: [],
      // 动态数据
      manyData: [],
      // 添加参数对话款显示
      addDialogVisible: false,
      // 添加表单验证规则
      addRules: {
        name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      // 添加表单数据
      addFormData: {},
      // 修改参数对话款显示
      editDialogVisible: false,
      // 修改表单数据
      editForm: {},
      // 参数ID
      paramsId: "",
    };
  },
  created() {
    this.getCascaderDate();
  },
  methods: {
    async getCascaderDate() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200) {
        return this.$message("级联选择器数据请求失败！");
      }
      this.menuInfo = res.data;
      console.log(res);
    },
    // 级联选择器发生改变触发
    cateHandleChange() {
      // 如果不是三级分类
      if (this.selectedKeys.length != 3) {
        this.selectedKeys = [];
        this.manyData = [];
        this.onlyData = [];
        return;
      }

      this.getParamsDate();
    },

    handleClick() {
      this.getParamsDate();
      console.log(this.activeName);
    },

    // 获取列表数据
    async getParamsDate() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return;
      }
      this.$message.success(res.meta.msg);

      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // item.inputVisible = false;
        // item.inputValue = "";
        // 让每行的数据身上都有单独的inputVisible  inputValue 每行之间互不影响
        this.$set(item, "inputVisible", false);
        this.$set(item, "inputValue", "");
      });
      if (this.activeName == "only") {
        this.onlyData = res.data;
      } else {
        this.manyData = res.data;
      }
      console.log(this.onlyData);
    },
    // 重置表单
    closeDialog() {
      this.$refs.addRuleForm.resetFields();
    },
    // 进行添加参数或者添加属性表单预校验以及网络请求
    addFormReq() {
      this.$refs.addRuleForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.info("取消添加");
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addFormData.name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status != 201) {
          this.$message.error("添加失败");
        }
        this.$message.success("添加参数成功！");
        this.getParamsDate();
        this.addDialogVisible = false;
        console.log(res);
      });
    },
    // 根据ID查询数据
    async editParams(row) {
      // 属性ID
      this.paramsId = row.attr_id;
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${this.paramsId}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("查询失败");
      }
      this.editForm = res.data;

      console.log(this.editForm);
      // console.log(row);
      // console.log(this.cateId);
      this.editDialogVisible = true;
    },
    // 重置修改表单
    editClose() {
      this.$refs.editRuleForm.resetFields();
    },
    // 表单预校验以及提交参数
    editFormReq() {
      this.$refs.editRuleForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.info("取消删除");
        }
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.paramsId}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status != 200) {
          return this.$message.error("请求失败");
        }
        this.$message.success("修改成功");
        this.getParamsDate();
        console.log(res);
        this.editDialogVisible = false;
      });
    },
    // 删除属性
    async deleteParams(row) {
      const ress = await this.$confirm(
        "此操作将永久删除该属性, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (ress != "confirm") {
        return this.$message.info("取消删除");
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getParamsDate();
      console.log(res);
      console.log(ress);
    },
    // 标签输入框
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 如果没有return则证明输入正确的内容，需要做正确的处理
      // 先把row.inputValue绑定的值加入row.attr_vals
      row.attr_vals.push(row.inputValue.trim());
      // 发送请求
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("操作失败");
      }
      this.$message.success("操作成功");
      row.inputValue = "";
      console.log(res);
    },
    showInput(row) {
      row.inputVisible = true;
      // this.$nextTick确保当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleClose(i, row) {
      // 从数组中删除
      row.attr_vals.splice(i, 1);
      // 发送请求
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("操作失败");
      }
      this.$message.success("操作成功");
    },
  },
  computed: {
    isBtn() {
      if (this.selectedKeys.length == 3) {
        return false;
      } else {
        return true;
      }
    },
    // 分类ID
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2];
      }
      return null;
    },
    isOk() {
      if (this.activeName == "only") {
        return "静态属性";
      } else {
        return "动态参数";
      }
    },
  },
};
</script>

<style lang='less' scoped>
.alert {
  margin-bottom: 20px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>